package cn.chiship.bs.api.core.util;

import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 格式化dto验证错误信息
 *
 * @author lj
 */
public class BindingResultUtil {
    private BindingResultUtil() {
    }

    public static BaseResult format(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            Map<String, Object> errorMap = new HashMap<>(2);
            List<ObjectError> objectErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : objectErrors) {
                String key = null;
                String errorMsg = null;
                if (objectError instanceof FieldError) {
                    FieldError fieldError = (FieldError) objectError;
                    key = fieldError.getField();
                } else {
                    key = objectError.getObjectName();
                }
                errorMsg = objectError.getDefaultMessage();
                errorMap.put(key, errorMsg);
            }
            return BaseResult.error(BaseResultEnum.PARAM_CHECK_FAILED, errorMap);
        } else {
            return BaseResult.ok(null);
        }
    }
}
